package com.cloudstudy.controller;

import com.cloudstudy.entity.CommonResult;
import com.cloudstudy.entity.Payment;
import com.cloudstudy.service.PaymentFeignService;
import com.cloudstudy.tool.JsonTool;
import com.cloudstudy.tool.LogTool;
import com.cloudstudy.tool.SpringTool;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Timer;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @auther zzyy
 * @create 2020-02-20 0:05
 */
@RestController
@Slf4j
public class OrderFeignController
{
    public static AtomicInteger count = new AtomicInteger(0);

    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") String id)
    {
        return paymentFeignService.getPaymentById(id);
    }

    @GetMapping(value = "/get3/{id}")
    public void get3(@PathVariable("id") String id)
    {
        Timer timer = new Timer();
        // 在1秒后,每隔3秒执行一次
        timer.schedule(new TimerTaskTest(id), 1000, 3000);
    }

    @GetMapping(value = "/consumer/payment/feign/timeout")
    public String paymentFeignTimeout()
    {
        // OpenFeign客户端一般默认等待1秒钟
        return paymentFeignService.paymentFeignTimeout();
    }

    @GetMapping(value = "/test")
    public String test() throws Exception
    {
        count.getAndIncrement();
        System.out.println("count: "+count);
        Thread.sleep(1000000);
        // OpenFeign客户端一般默认等待1秒钟
        return "success";
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Accessors(chain = true)
class TimerTaskTest extends java.util.TimerTask{

    String id;

    @Override
    public void run() {
        // TODO Auto-generated method stub
        PaymentFeignService paymentFeignService = SpringTool.getSpringBean("com.cloudstudy.service.PaymentFeignService");
        CommonResult<Payment> commonResult = paymentFeignService.getPaymentById(id);
        OrderFeignController.count.getAndIncrement();
        System.out.println("count: "+OrderFeignController.count+", commonResult: "+JsonTool.toJson(commonResult));
    }
}